initPageDefault();
/******全局常量 ******/
var head = {
	'name':'节点名称',
	'type':'类型',
	'online':'在线状态',
	'operation':'操作'
};
var rolesColor = [ 'label-primary','label-success','label-info','label-default'];
var linkTableHead=['用户','时间','时长','状态','详情'];
var linkTable;
var nodeTable;
/****** 定义页面组件 ******/
/**
 * 我的云节点表格行组件
 */
var NodeTableTr = React.createClass({
    componentDidMount:function(){
        var $trs = $(this.refs.trs);
        $trs.find("[data-toggle='tooltip']").tooltip();
        
       
    },
    componentDidUpdate:function(){
        var $trs = $(this.refs.trs);
        $trs.find("[data-toggle='tooltip']").tooltip();
    },
    
	render:function(){
		var name = this.props.name;
		var onlineTime = this.props.onlineTime;
		var type = '-';
//		var rolse;
//		if(this.props.roles != null && this.props.roles.length > 0){
//			rolse = [];
//			for(var i in this.props.roles){
//				var lable = 'label ' + rolesColor[i];
//				rolse.push(<span className={lable}>{this.props.roles[i]}</span>);
//				rolse.push(<br/>)
//			}
//		}
		var online;
		var onlineInfo = getDateDiff(onlineTime);
		if(this.props.online){
			online = <p><span className='label label-success' data-toggle='tooltip' title={onlineInfo}>在线 </span></p>
		}else{
			online = <span className='label label-default'>离线</span>
		}
		var operationComp = <NodeTableTrOperationGroup nodeId={this.props.id} nodeName={this.props.name}></NodeTableTrOperationGroup>;
		return <tr className='node-tr' ref='trs'>
					<td >{name}</td>
					<td >{type}</td>
					<td >{online}</td>
					<td>{operationComp}</td>
			  </tr>;
	}
});
/**
 * 我的云节点表格行操作按钮组件
 */
var NodeTableTrOperationGroup = React.createClass({	
	componentDidMount:function(){
		var $btns = $(this.refs.btns);
		$btns.find("[data-toggle='tooltip']").tooltip();
	},
	editNode:function(){
		layer.open({
			  type: 1,
			  area: ['720px','420px'],
			  title: false, 
			  content: $('#edit-node'), 
		});
	},
	nodeDetail:function(){
		location.href = CTX_PATH + '/console/node/detail?nodeId='+this.props.nodeId;	
	},
	checkHealth:function(){
		healCard.setState({name:this.props.nodeName,id:this.props.nodeId});
		$.ajax({
			url : CTX_PATH + '/console/node/health',
			type:'post',
			data : {
				token:$.cookie('token'),
				hostId:this.props.nodeId
			},
			success:function(rtn){
				console.log(rtn);
				if(!rtn.error){
					var data = rtn.data;
					if(data != null){
						var report = data.report;
						var items = [];
						for(var i in report.items){
							var it = report.items[i];
							items.push({
								name : it.name,
								state : it.status,
							});
						}
						healCard.setState({
							time:data.date,
							score:report.rank,
							items:items
						});
					}
				}else{
					layer.msg('数据加载失败');
					console.error(rtn.msg);
				}
			}
		});
		var area;
		if(isMobileClient()){
			area=['250px','500'];
		}else{
			area=['420px', '720px'];
		}
		layer.open({
		  type: 1,
		  area: area,
		  title: false, 
		  content: $('#health-card'), 
		  cancel:function(){
				healCard.setState({
		        	nodeId:null,
		        	items:null,
		        	time:null,
		        	score:0,
		        });
		  }
		});
	},
	lookLogs:function(){
		//加载日志树
		$.ajax({
			url:CTX_PATH + '/console/node/log/tree',
			type:'post',
			data:{
				token:$.cookie('token'),
				hostId:this.props.nodeId
			},
			success:function(rtn){
				console.log('log tree:%o',rtn);
				if(!rtn.error){
					var logs = rtn.data.childs;
					if(logs != null && logs.length > 0){
						var tree = [];
						for(var i in logs){
							var l = logs[i];
							tree.push(completeTreeData(l)); 
						}
						$('#log-tree').html('');
						$('#log-tree').treeview({
							data: tree,
							onNodeSelected: function (event, data) {
		                        console.log('node data:%o',data);
		                        if(data.isLog){
		                        	$('#log-name').val(data.text);
		                        	$('#log-path').val(data.value);
		                        }
		                        
		                    }
						}); 
					}else{
						$('#log-tree').html('暂无日志');
					}
				}else{
					layer.msg('数据加载失败');
					console.error(rtn.msg);
				}
			}
		});
		layer.open({
			  type: 1,
			  area: ['80%', '600px'],
			  title: '在线日志 - '+this.props.nodeName, 
			  content: $('#online-log'), 
			  cancel: function(index, layero){ 
				  layer.close(index)
				  $('#log-show').empty();
				  $('#log-form input').val('');
				  return false; 
			  }    
		});
		$('#node-id').val(this.props.nodeId);
	},
	webSsh:function(){
		var index = layer.open({
			  type: 2,
			  title: this.props.nodeName+ ' - web ssh',
			  area: ['720px', '520px'],
			  anim: 2,
			  shade: 0,
			  offset: 'rb',
			  content: CTX_PATH + '/console/node/ssh?id='+this.props.nodeId,
			  zIndex: layer.zIndex ,//重点1
			  success: function(layero,index){
			    layer.setTop(layero); //重点2
			  },
			});
	},
	lookLinks:function(){
		//查看连接
		linkTable.setState({keyWords:{nodeId:this.props.nodeId}});
		var index = layer.open({
			  type: 1,
			  area: ['720px', '500px'],
			  title: this.props.nodeName + ' - 远程连接', //不显示标题
			  content: $('#link-list'), 
		});
		
		setTimeout(function(){
			linkList.selectCommnLink();
		},500);
	},
	setMonitor:function(){
		// 监控设置
		layer.open({
			  type: 1,
			  area: ['700px', '600px'],
			  title: '监控设置- '+this.props.nodeName, 
			  content: $('#monitor-setting'), 
		});
		var initState = monitorTable.getInitialState();
		var keyWords = {
			nodeId:this.props.nodeId
		}
		monitorTable.setState({nodeId:this.props.nodeId});
		loadMonitorTableData(keyWords,1,5);
	},
	restartNode:function(){
		var nodeId = this.props.nodeId;
		layer.confirm('确定要重启节点？', {icon: 3, title:'提示'}, function(index){
			$.ajax({
				url:CTX_PATH+'/console/node/restart',
				type:'post',
				data:{
					token:$.cookie('token'),
					hostId:nodeId
				},
				success:function(rtn){
					console.log('restart node:%o',rtn);
					if(!rtn.error){
						layer.msg('重启节点发送成功');
					}else{
						console.error('重启节点失败（'+rtn.error+'）');
						layer.msg('重启节点发送失败');
					}
				}
			});
		  layer.close(index);
		});
	},
	shutdownNode:function(){
		var nodeId = this.props.nodeId;
		layer.confirm('确定要关闭节点？', {icon: 3, title:'提示'}, function(index){
			$.ajax({
				url:CTX_PATH+'/console/node/shutdown',
				type:'post',
				data:{
					token:$.cookie('token'),
					hostId:nodeId
				},
				success:function(rtn){
					console.log('shutdown node:%o',rtn);
					if(!rtn.error){
						layer.msg('关闭节点发送成功');
					}else{
						console.error('关闭节点失败（'+rtn.error+'）');
						layer.msg('关闭节点发送失败');
					}
				}
			});
			layer.close(index);
		});
		
	},
	devopsHelp:function(){
		//TODO 运维帮助
		functionRepair();
	},
	shareNode:function(){
		//共享基站
		var nodeName = this.props.nodeName;
		
		$shareTime.val(null);
		$shareNodeId.val(this.props.nodeId);
		$shareUnit.val(0);
		$shareCpu.val(0);
		$shareMemory.val(0);
		
		$.ajax({
			url:CTX_PATH+'/console/node/share/info',
			data:{
				token:$.cookie('token'),
				hostId:this.props.nodeId
			},
			type:'post',
			success:function(rtn){
				console.log('share host:%o',rtn);
				if(!rtn.error){
					var data = rtn.data;
					$cpuMax.val(data.totalCpuNum);
					$memoryMax.val(data.totalMemoryNum);
					$('#share-cpu-max-1').val(data.totalCpuNum);
					$('#share-memory-max-1').val(data.totalMemoryNum);
					if(data.state == 0){
						var index = layer.open({
							  type: 1,
							  area: ['720px', '500px'],
							  title: nodeName + ' - 共享基站', 
							  content: $('#share-node'), 
						});
					}else{
						layer.msg('节点已共享');
					}
				}else{
					console.error(rtn.msg+'('+rtn.error+')');
					layer.msg('获取节点共享信息失败');
				}
			}
		});
		
	},
	restartVm:function(){
		$.ajax({
			url:CTX_PATH+'/console/node/vm/restartAll',
			data:{
				hostId:this.props.nodeId
			},
			success:function(rtn){
				console.log(rtn);
				if(!rtn.error){
					layer.msg('重启节点虚拟机操作已发送');
				}else{
					layer.msg('重启节点虚拟机操作失败');
				}
			}
		});
	},
	restartTerminal:function(){
		$.ajax({
			url:CTX_PATH+'/console/node/terminal/restartAll',
			data:{
				hostId:this.props.nodeId
			},
			success:function(rtn){
				console.log(rtn);
				if(!rtn.error){
					layer.msg('重启节点终端操作已发送');
				}else{
					layer.msg('重启节点终端操作失败');
				}
			}
		});
	},
	render : function(){
		
		var btns = [];
		var moreBtns = [];
		var more;
		//适配不同分辨率显示不同按钮个数
		if(!isMobileClient()){
			btns.push(<button type='button' onClick={this.nodeDetail} className='btn btn-default'  data-toggle='tooltip' title='节点详情'><i className='icon-info-sign'></i></button>);
			btns.push(<button type='button' onClick={this.checkHealth} className='btn btn-default' data-toggle='tooltip' title='健康检查'><i className='icon-heart'></i></button>);
			btns.push(<button type='button' onClick={this.webSsh} className='btn btn-default'  data-toggle='tooltip' title='网页ssh'><i className='icon-desktop'></i></button>);
			btns.push(<button type='button' onClick={this.lookLogs} className='btn btn-default'  data-toggle='tooltip' title='查看日志'><i className='icon-book'></i></button>);
		}else{
			moreBtns.push(<li><a href='#' onClick={this.nodeDetail}>节点详情</a></li>);
			moreBtns.push(<li><a href='#' onClick={this.checkHealth}>健康检查</a></li>);
			moreBtns.push(<li><a href='#' onClick={this.webSsh}>网页ssh</a></li>);
			moreBtns.push(<li><a href='#' onClick={this.lookLogs}>查看日志</a></li>);
			more = '更多';
		}
		moreBtns.push(<li><a href='#' onClick={this.lookLinks}>查看连接</a></li>);
		moreBtns.push(<li><a href='#' onClick={this.setMonitor}>监控设置</a></li>);
		moreBtns.push(<li><a href='#' onClick={this.shareNode}>共享基站</a></li>);
		moreBtns.push(<li><a href='#' onClick={this.devopsHelp}>运维帮助</a></li>);
		moreBtns.push(<li><a href='#' onClick={this.restartVm}>重启虚拟机</a></li>);
		moreBtns.push(<li><a href='#' onClick={this.restartTerminal}>重启终端</a></li>);
		moreBtns.push(<li role='presentation' className='divider'></li>);
		moreBtns.push(<li><a href='#' onClick={this.restartNode}>重启节点</a></li>);
		moreBtns.push(<li><a href='#' onClick={this.shutdownNode}>关闭节点</a></li>);
	
		return <div className='btn-group' ref='btns'>
		       {btns}
		        <div className='btn-group'>
		          <button type='button' className='btn btn-default dropdown-toggle' data-toggle='dropdown'>
		          	{more}
		          	<span className='caret'></span>
		          </button>
		          <ul className='dropdown-menu  pull-right'>
		            {moreBtns}
		          </ul>
		        </div>
		      </div>
		     ;
	}
});

/**
 * 健康卡组件
 */
var HealthCard =  React.createClass({
	 getInitialState: function () {  
	        return {
	        	nodeId:null,
	        	items:null,
	        	time:null,
	        	score:0,
	        };  
	},
	check:function(){
		var nodeId = this.state.id;
		$.ajax({
			url:CTX_PATH + '/console/node/health/check',
			type:'post',
			data:{
				token:$.cookie('token'),
				hostId:nodeId
			},
			success:function(rtn){
				console.log('health check data:%o',rtn);
				if(!rtn.error){
					layer.msg('自检操作已发送')
				}else{
					layer,msg('自检操作发送失败！')
				}
			}
		});
	},
	render:function(){
		var errorNum;
		var healItemComps ;
		var items = this.state.items;
		if( items != null && items.length ){
			healItemComps = [];
			for(var i in items ){
				var it = items[i];
				healItemComps.push(<li className='list-group-item'>{it.name}<span className={ 'badge ' + ( it.state?'success':'danger')}>{ it.state?'Ok':'Error'}</span></li>);
				if(!it.state){
					if(errorNum == null){
						errorNum = 1;
					}else{
						errorNum ++;
					}
				}
			}
			healItemComps = <ul className='list-group'>{healItemComps}</ul>
		}else{
			healItemComps = <div className='empty'>无检查项</div>;
		}
	
		var time = '-';
		if(this.state.time != null){
			time = new Date(this.state.time).format('yyyy·MM·dd hh:mm:ss')
		}
		return <div className='health-card'>
			<div className='health-card-head'>
				<div className='row '>
					<span className='health-card-node'>{this.state.name}</span>
				</div>
				<div className='row '>
					<div className='col-md-4 col-xs-4 health-card-icon'>
						<img src={CTX_PATH+'/img/health.png'}></img>
					</div>
					<div className='col-md-8 col-xs-8 '>
						<div className='col-md-12 health-card-score'>
							<span className='title'>得分: </span>
							<span className='value'>{this.state.score} </span>
						</div>
						<div className='col-md-12 health-card-percent'>
							<div className='progress'>
								  <div className='progress-bar' role='progressbar' aria-valuenow={this.state.score} aria-valuemin='0' aria-valuemax='100' style={{width:this.state.score+'%'}}> </div>
							</div>
						</div>
					</div>
				</div>
				<div className='row'>
					<div className='col-md-12 health-card-time'>
						<span>日期：</span><span>{time}</span>
					</div>
				</div>
				<div className='row'>
					<div className='col-md-12 health-card-check'>
						<a href='#' className='btn-glow primary' onClick={this.check}>检查</a>
					</div>
				</div>
			</div>
			<div className='health-card-body'>
				<div className='panel panel-default'>
				  <div className='panel-heading'>检查项 <span className='badge danger'>{errorNum}</span></div>
				  {healItemComps}
				</div>
			</div>
		</div>
		;
	}
});
/**
 * 节点连接列表组件
 */
var NodeLinkList = React.createClass({
    getInitialState: function () {  
        return {
        	nodeName:'',
        };  
    },
	selectCommnLink:function(){
		// 选中通用按钮并重新加载表
		$(this.refs.table).find('.link-type button').removeClass('active');
		$(this.refs.table).find('.common').addClass('active');
		if(linkTable.state.keyWords.type != 'common'){
			linkTable.state.keyWords.type = 'common';
			linkTable.state.pageNum = 1;
			linkTable.state.pageSize = 5;
			loadNodeLinkTableData(linkTable.state.keyWords,linkTable.state.pageNum,linkTable.state.pageSize);
		}
	},
	selectVmLink:function(){
		// 选中虚拟机按钮并重新加载表
		$(this.refs.table).find('.link-type button').removeClass('active');
		$(this.refs.table).find('.vm').addClass('active');
		if(linkTable.state.keyWords.type != 'vm'){
			linkTable.state.keyWords.type = 'vm';
			linkTable.state.pageNum = 1;
			linkTable.state.pageSize = 5;
			loadNodeLinkTableData(linkTable.state.keyWords,linkTable.state.pageNum,linkTable.state.pageSize);
		}
	},
	componentDidMount:function(){
		// 渲染完后再渲染列表
		var table = this.refs.table;
		var barComp =[ <div className='btn-group pull-right link-type'>
				        <button onClick={this.selectCommnLink} className='glow left large common'>通用</button>
				        <button onClick={this.selectVmLink} className='glow right large vm'>虚拟机</button>
				    </div>];
		linkTable = ReactDOM.render(
				<TeOpsTable title='节点连接' heads={linkTableHead} barCompnents={barComp} paging={true} loadData={loadNodeLinkTableData} ></TeOpsTable>,
				table
		);
	},
	render : function(){
		return 	<div className='link-list'>
					<div className='row link-list-head'></div>
					<div className='row'>
						<div className='col-md-1'></div>
						<div className='col-md-10'>
							<div ref='table'></div>
						</div>
					</div>
				</div>
	}
});
/**
 * 连接列表 - 行组件
 */
var NodeLinkTableTr = React.createClass({
	render :function(){
		var user = this.props.user;
		var createTime = '-';
		if(this.props.createTime){
			var date = new Date(this.props.createTime);
			createTime = date.format('yyyy·MM·dd hh:mm:ss');
		}
		var useTime = '-';
		var state;
		switch(this.props.state){
		case 0:
			state = '等待连接';
			break;
		case 1:
			var timestamp = new Date().getTime() - this.props.createTime;
			if(timestamp >= 1000){
				useTime = timestampFormt(timestamp);
			}else{
				useTime = '刚刚';
			}
			state = '连接中';
			break;		
		case 2:
			state = '连接失败';
			break;
		case 3:
			state = '连接超时';
			break;
		case 4:
			state = '连接已使用';
			break;
		case 5:
			state = '连接已关闭';
			break;
		case 6:
			state = '连接准备关闭';
			break;
		case 7:
			state = '连接被禁止';
			break;
		case 1000:
			if(this.props.useTime >= 1000){
				useTime = timestampFormt(this.props.useTime);
			}
			state = '已结束';
			break;
		}
		var detail = this.props.detail;
		return <tr className='link-tr'>
					<td>{user}</td>
					<td>{createTime}</td>
					<td>{useTime}</td>
					<td>{state}</td>
					<td>{detail}</td>
			  </tr>
	}
});

/**
 * 监控列表 - 行组件
 */

var MonitorTableTr = React.createClass({
	render :function(){
		var operationComp = <MonitorTableTrOperationGroup itemKey={this.props.itemKey}></MonitorTableTrOperationGroup>;
		var name,key,state,enable;
		name = this.props.name;
		key = this.props.itemKey;
		
		switch(this.props.enable){
		case 1:
			enable = <span className='badge success'>已启用</span>
			break;
		case 2:
			enable = <span className='badge danger'>已禁用</span>
			break;
		}
		
		switch(this.props.state){
		case 1:
			state = <span className='badge success'>正常</span>
			break;
		case 2:
			state = <span className='badge danger'>掉线</span>
			break;
		}
		
		return <tr className='teops-tr'>
					<td>{name}</td>
					<td>{key}</td>
					<td>{enable}</td>
					<td>{state}</td>
					<td>{operationComp}</td>
			  </tr>
	}
});
/**
 * 监控列表 - 行组合按钮组件
 */
var MonitorTableTrOperationGroup = React.createClass({
	enableMonitor:function(){
		enableNodeMonitor(monitorTable.state.nodeId,this.props.itemKey);
		
	},
	disableMonitor:function(){
		disableNodeMonitor(monitorTable.state.nodeId,this.props.itemKey);
	},
	render:function(){
		return <div className='btn-group'>
					<button type='button' className='btn btn-default' onClick={this.enableMonitor} ><i className='icon-play'/></button>
					<button type='button' className='btn btn-default' onClick={this.disableMonitor}><i className='icon-pause'/></button>
	      		</div>;
	}
});
var $unit,$cpuMax,$memoryMax,$shareUnit,$shareCpu,$shareMemory,$shareTime,$shareNodeId;
var ShareNodePanel = React.createClass({
	componentDidMount:function(){
		$unit = $('#res-unit');
		$cpuMax = $('#share-cpu-max');
		$memoryMax = $('#share-memory-max');
		$shareUnit = $('#share-unit');
		$shareCpu = $('#share-cpu');
		$shareMemory = $('#share-memory');
		$shareTime = $('#share-time');
		$shareNodeId =  $('#share-host-id');
		$shareUnit.val(0);
		$shareCpu.val(0);
		$shareMemory.val(0);
	},
	addUnit:function(){
		var unit = $shareUnit.val();
		if(unit == null){
			unit = 0;
		}
		unit = parseInt(unit) +1;
		if(!setCpuMemory(unit)){
			return
		}

		$shareUnit.val(unit);
	},
	minusUnit:function(){
		var unit = $shareUnit.val();
		if(unit == null){
			unit = 0;
		}
		if(unit <= 0){
			return ;
		}
		unit = parseInt(unit) -1
		setCpuMemory(unit);
		$shareUnit.val(unit);
		$shareUnit.trigger('change');
	},
	shareNode:function(){
		
		var hostId = $shareNodeId.val();
		var cpuNum = $shareCpu.val();
		var memoryNum = $shareMemory.val();
		var time = $shareTime.val();
		console.log(time)
		if(cpuNum == null || parseInt(cpuNum) < 1){
			layer.msg('请选择CPU核数');
			return;
		}else if(memoryNum == null || parseInt(memoryNum) < 1){
			layer.msg('请选择内存容量');
			return;
		}else if(time == null || time == '' || parseInt(time) < 1){
			layer.msg('请选择共享时长');
			return;
		}
		
		$.ajax({
			url:CTX_PATH+'/console/share/node',
			type:'post',
			data:{
				token:$.cookie('token'),
				hostId:hostId,
				cpuNum:cpuNum,
				memoryNum:memoryNum,
				time:time
			},
			success:function(rtn){
				console.log('share node:%o',rtn);
				if(!rtn.error){
					layer.msg('共享成功');
				}else{
					layer.msg('共享失败');
					console.error(rtn.msg+'('+rtn.error+')')
				}
			}
			
		});
	},
	render:function(){
		return <div>
				<form className='form-horizontal share-node-setting'>
				  <input id='share-host-id' type="hidden" />
				  <input id='share-cpu-max' type="hidden" />
				  <input id='share-memory-max' type="hidden" />
				  <div className='form-group'>
				    <label htmlFor='res-unit' className='col-sm-2 control-label'>可用CPU</label>
				    <div className='col-sm-3'>
					    <div className="input-group">
					      <input id='share-cpu-max-1' readOnly='readonly' type="text" className="form-control" />
					      <span className='input-group-addon'>核</span>
					    </div>
				    </div>
				  </div>
				  <div className='form-group'>
				    <label htmlFor='res-unit' className='col-sm-2 control-label'>可用内存</label>
				    <div className='col-sm-3'>
				    <div className="input-group">
				      <input id='share-memory-max-1' readOnly='readonly' type="text" className="form-control" />
				      <span className='input-group-addon'>GB</span>
				    </div>
			    </div>
				  </div>
				  <div className='form-group'>
				    <label htmlFor='res-unit' className='col-sm-2 control-label'>资源单元</label>
				    <div className='col-sm-10'>
					    <div className='ui-select'>
		                    <select id='res-unit'>
		                        <option selected='' value='1'>普通（1核1G）</option>
		                    </select>
		                </div>
				    </div>
				  </div>
				  <div className='form-group'>
				    <label htmlFor='share-unit' className='col-sm-2 control-label'>共享单元</label>
				    <div className='col-sm-3'>
					    <div className="input-group">
					     
					      <input id='share-unit' readOnly='readonly' type="text" className="form-control" />
					      <span className='input-group-addon'>个</span>
					    </div>
				    </div>
				    <div className="btn-group">
				        <button className="btn btn-default" type="button" onClick={this.addUnit}>加</button>
				        <button className="btn btn-default" type="button" onClick={this.minusUnit}>减</button>
				    </div>
				  </div>
				  <div className='form-group'>
				    <label htmlFor='share-cpu' className='col-sm-2 control-label'>共享CPU</label>
				    <div className='col-sm-3'>
					    <div className="input-group">
					      <input id='share-cpu' readOnly='readonly' type="text" className="form-control" />
					      <span className='input-group-addon'>核</span>
					    </div>
				    </div>
				  </div>
				  <div className='form-group'>
				    <label htmlFor='share-memory' className='col-sm-2 control-label'>共享内存</label>
				    <div className='col-sm-3'>
					    <div className="input-group">
					      <input id='share-memory' readOnly='readonly' type="text" className="form-control" />
					      <span className='input-group-addon'>GB</span>
					    </div>
				    </div>
				  </div>
				  <div className='form-group'>
				    <label htmlFor='share-time' className='col-sm-2 control-label'>共享时间</label>
				    <div className='col-sm-3'>
					    <div className="input-group">
					      <input id='share-time'  type="text" className="form-control" />
					      <span className='input-group-addon'>小时</span>
					    </div>
				   </div>
				  </div>
				  <div className='form-group'>
					  <div className='col-sm-3 col-md-offset-1'>
						  <a className="btn-glow primary" onClick={this.shareNode}>共享</a>
					  </div>
				  </div>
				</form>
		</div>;
	}
});

/****** 定义函数 ******/
function searchCall(val){
	var initState = nodeTable.getInitialState();
	var keyWords = initState.keyWords;
	keyWords.nodeName = val;
	loadNodeTableData(keyWords,initState.pageNum,initState.pageSize);
}
function searchNode(){
	var val ;
	val = $('#node-table .search').val();
	searchCall(val)
}
function resetTable(){
	var initState = nodeTable.getInitialState();
	loadNodeTableData(null,initState.pageNum,initState.pageSize);
}
function initNodeTable(){
	var barComp = [
		<TeOpsTableSearch placeholder='搜索节点名...' enterCall={searchCall} ></TeOpsTableSearch>,
		<TeOpsTableBtn name='搜索' type='primary' icon='icon-search'  click={searchNode}></TeOpsTableBtn>,
		<TeOpsTableBtn name='重置' type=''   click={resetTable}></TeOpsTableBtn>
	];
	
	nodeTable = ReactDOM.render(
		<TeOpsTable title='我的云节点' heads={head} barCompnents={barComp} paging={true} loadData={loadNodeTableData} ></TeOpsTable>,
		document.getElementById('node-table')
	);
	var initState = nodeTable.getInitialState();
	loadNodeTableData(null,initState.pageNum,initState.pageSize);
}

var monitorTable;
var monitorHead = ['名称','key','启用','状态','操作'];
var monitorFilters = {'名称':'name','key':'key'};
function initMonitorTable(){
	var barComp = [
		<TeOpsTableFilter filters={monitorFilters} ></TeOpsTableFilter>,
		<TeOpsTableSearch placeholder='搜索...' enterCall={searchMonitorCall} ></TeOpsTableSearch>,
		<TeOpsTableBtn name='搜索' type='primary' icon='icon-search'  click={searchMonitor}></TeOpsTableBtn>,
		<TeOpsTableBtn name='重置' type=''   click={resetMonitorTable}></TeOpsTableBtn>
	];
	
	monitorTable = ReactDOM.render(
		<TeOpsTable title='我的云节点' heads={monitorHead} barCompnents={barComp} paging={true} loadData={loadMonitorTableData} ></TeOpsTable>,
		document.getElementById('monitor-list')
	);
}
function loadMonitorTableData(keyWords,pn,ps){
	var nodeId,key,name;
	if(keyWords != null){
		nodeId = keyWords.nodeId;
		key = keyWords.key;
		name = keyWords.name;
	}
	$.ajax({
		url:CTX_PATH + '/console/node/monitor/page',
		type:'post',
		data:{
			token:$.cookie('token'),
			hostId:nodeId,
			key:key,
			name:name,
			pageNum:pn,
			pageSize:ps
		},
		success:function(rtn){
			console.log('monitor data：%o',rtn);
			if(!rtn.error){
				var data = rtn.data;
				var list = data.list;
				var pn = data.pageNum;
				var ps = data.pageSize;
				var total = data.total;
				var rows = [];
				for(var i in list){
					var r = list[i];
					rows.push(<MonitorTableTr id={r.id} name={r.name} itemKey={r.key} state={r.state} enable={r.enable} ></MonitorTableTr>);
				}
				monitorTable.setState({ 
					'keyWords':{
						nodeId:nodeId,
						name:name,
						key:key,
					},
					'rows':rows,
					'pageNum':pn,
					'pageSize':ps,
					'total':total
				});
				
			}else{
				console.log(rtn.msg);
				layer.msg('加载数据失败')
			}
		}
	});
	
}
/**
 * 计算在线时间
 */
function getDateDiff(onlineTime){
    var result = "";
    var second = 1000;
    var minute = 1000 * 60;
    var hour = minute * 60;
    if(onlineTime < 0){return;}
    var hourC =onlineTime/hour;
    var minC =onlineTime/minute;
    var sec = onlineTime/second;
    if(hourC>=1){
        result="" + parseInt(hourC) +"小时前";
    }
    else if(minC>=1){
        result="" + parseInt(minC) +"分钟前";
    }
    else if(sec >0 && sec <=59){
        result="" + parseInt(sec)+"秒前";
    }else{
        result="" +"-秒前";
    }
    return result;
    console.log(result);
}
function searchMonitorCall(val){
	var key = $('#monitor-list .table-filter select').val();
	var keyWords = {
		nodeId:monitorTable.state.keyWords.nodeId
	};
	keyWords[key] = val;
	loadMonitorTableData(keyWords,1,5);
}
function searchMonitor(){
	searchMonitorCall($('#monitor-list .search').val());
}
function resetMonitorTable(){
	var keyWords = {
		nodeId:monitorTable.state.keyWords.nodeId
	}
	loadMonitorTableData(keyWords,1,5);
}
/**
 * 加载节点数据
 */
function loadNodeTableData(keyWord,pn,ps){
	var nodeName = null;
	if(keyWord != null){
		nodeName = keyWord.nodeName;
	}
	$.ajax({
		url:CTX_PATH+'/console/node/page',
		type:'post',
		data:{
			token:$.cookie('token'),
			pageNum:pn,			
			pageSize:ps,
			name:nodeName
		},
		success:function(rtn){
			console.log('my node data:%o',rtn);
			if(!rtn.error){
				var data = rtn.data;
				var list = data.list;
				var pn = data.pageNum;
				var ps = data.pageSize;
				var total = data.total;
				var rows = [];
				for(var i in list){
					var r = list[i];
					rows.push(<NodeTableTr  id={r.id} name={r.name} roles={r.roles} type={r.type} config={r.config} online={r.online} onlineTime={r.onlineTime} ></NodeTableTr>);
				}
				nodeTable.setState({ 
					'keyWords':{
						nodeName:nodeName
					},
					'rows':rows,
					'pageNum':pn,
					'pageSize':ps,
					'total':total
				});
			}
		},
		error:function(){
			
		}
	});
	
}
/**
 * 加载节点连接表格数据
 */
function loadNodeLinkTableData(keyWord,pn,ps){
	var type;
	if(keyWord != null){
		type = keyWord.type;
	}else{
		type = 'common';
	}
	$.ajax({
		url:CTX_PATH+'/console/node/link/page',
		type:'post',
		data:{
			token:$.cookie('token'),
			pageNum:pn,			
			pageSize:ps,
			type:type,
			hostId:keyWord.nodeId
		},
		success:function(rtn){
			console.log('load link data:%o',rtn);
			if(!rtn.error){
				var data = rtn.data;
				var rows = [];
				var list = data.list;
				var pn = data.pageNum;
				var ps = data.pageSize;
				var total = data.total;
				if(list != null && list.length > 0){
					for(var i in list){
						var r = list[i];
						var detail ;
						if(type == 'common'){
							detail = '端口:'+r.port;
						}else if(type == 'vm'){
							detail = '虚拟机：'+r.vmName;
						}
						rows.push(<NodeLinkTableTr user={r.user} createTime={r.createTime} useTime={r.useTime} state={r.state} detail={detail}></NodeLinkTableTr>);
					}
				}
				linkTable.setState({ 
					'keyWords':keyWord,
					'rows':rows,
					'pageNum':pn,
					'pageSize':ps,
					'total':total
				});
			}else{
				layer.msg('数据加载失败');
				console.error(rtn.msg)
			}
		}
	});
}
/**
 * 组装bootstrap-tree数据
 */
function completeTreeData(data){
	var node = {};
	node.text = data.fileName;
	node.value = data.path;
	
	if( data.file){
		node.icon = 'icon-file-text grey';
	}else{
		node.icon = 'icon-folder-close grey';
	}
	
	if(data.childs != null && data.childs.length >0){
		node.nodes = [];
		for(var i in data.childs){
			var c = data.childs[i];
			node.nodes.push(completeTreeData(c));
		}
	}
	node.isLog = data.file;
	return node;
}
/**
 * 在线日志搜索
 */
function serachLog(nodeId,path,begin,num,keyword){
	$.ajax({
		url:CTX_PATH+'/console/node/log/online',
		type:'post',
		data:{
			token:$.cookie('token'),
			hostId:nodeId,
			logPath:path,
			beginLine:begin,
			showLineNum:num,
			keyWord:keyword
		},
		success:function(rtn){
			console.log('search log:%o',rtn)
			if(!rtn.error){
				$('#log-show').html(rtn.data);
			}else{
				layer.msg('数据加载失败');
				console.error(rtn.msg);
			}
		}
	});
}
/**
 * 启用节点监控项
 * 
 */
function enableNodeMonitor(nodeId,itemKeys){
	$.ajax({
		url:CTX_PATH + '/console/node/monitor/enable',
		type:'post',
		traditional:true,
		data:{
			token:$.cookie('token'),
			nodeId:nodeId,
			itemKeys:itemKeys
		},
		success:function(rtn){
			console.log('enable node monitor:%o',rtn);
			if(!rtn.error){
				layer.msg('启用监控项成功');
				monitorTable.firstPage();
			}else{
				console.error(rtn.msg);
				layer.msg('启用监控项失败');
			}
		}
	})
}
/**
 * 禁用节点监控项
 */
function disableNodeMonitor(nodeId,itemKeys){
	$.ajax({
		url:CTX_PATH + '/console/node/monitor/disable',
		type:'post',
		traditional:true,
		data:{
			token:$.cookie('token'),
			nodeId:nodeId,
			itemKeys:itemKeys
		},
		success:function(rtn){
			console.log('enable node monitor:%o',rtn)
			if(!rtn.error){
				layer.msg('禁用监控项成功');
				monitorTable.firstPage();
			}else{
				console.error(rtn.msg);
				layer.msg('禁用监控项失败');
			}
		}
	})
}

function setCpuMemory(unit){
	var cpu,memory;
	switch(parseInt($unit.val())){
	case 1:
		cpu = unit;
		memory = unit;
		break;
	}
	if(cpu > $cpuMax.val() ){
		layer.msg('达到cpu资源上限')
		return false;
	}
	
	if(memory > $memoryMax.val() ){
		layer.msg('达到内存资源上限')
		return false;
	}
	
	$shareCpu.val(cpu);
	$shareMemory.val(memory);
	
	return true;
}
/**
 * 渲染健康卡组件
 */
var healCard = ReactDOM.render(
	  <HealthCard ></HealthCard>,
	  document.getElementById('health-card')
);

var linkList = ReactDOM.render(
	<NodeLinkList></NodeLinkList>,
	document.getElementById('link-list')
);

var shareNodePanel = ReactDOM.render(
		<ShareNodePanel></ShareNodePanel>,
		document.getElementById('share-node')
);
$('#search-log').click(function(){
	var nodeId = $('#node-id').val();
	var path = $('#log-path').val();
	var begin = $('#log-begin').val();
	var num = $('#log-num').val();
	var keword = $('#log-keyword').val();
	serachLog(nodeId,path,begin,num,keword);
});
$('#reset-log').click(function(){
	$('#log-begin').val('');
	$('#log-num').val('');
	$('#log-keyword').val('');
});
initNodeTable();
initMonitorTable();